package com.wzdigit.wms.raw.service.backtosap;


import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.wzdigit.framework.Shift;
import com.wzdigit.mes.basic.api.BasicVendorApi;
import com.wzdigit.mes.basic.dto.VendorDTO;
import com.wzdigit.wms.basic.domain.asn.AsnDtl;
import com.wzdigit.wms.basic.domain.basic.Sku;
import com.wzdigit.wms.basic.domain.basic.Warehouse;
import com.wzdigit.wms.basic.domain.mapping.CodeMapping;
import com.wzdigit.wms.basic.domain.mid.IfPostback;
import com.wzdigit.wms.basic.domain.transfer.TransferDtl;
import com.wzdigit.wms.basic.domain.transfer.TransferHeader;
import com.wzdigit.wms.basic.enums.writeback.BackResultEnum;
import com.wzdigit.wms.basic.enums.writeback.OtherSystemEnum;
import com.wzdigit.wms.basic.enums.writeback.TopicEnum;
import com.wzdigit.wms.basic.mapper.core.basic.SkuMapper;
import com.wzdigit.wms.basic.mapper.core.basic.WarehouseMapper;
import com.wzdigit.wms.basic.mapper.core.mapping.CodeMappingMapper;
import com.wzdigit.wms.basic.service.code.CodeMappingService;
import com.wzdigit.wms.common.entity.StatusCode;
import com.wzdigit.wms.raw.service.mid.IfPostbackService;
import com.wzdigit.wms.web.service.wms2sap.outstore.ZDT_071_ReqCDK;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 调拨回写Service
 * Created by zyf on 2021/8/13 18:37
 */
@Service
@Slf4j
public class TransferAutoBackService {


    @Autowired
    SkuMapper skuMapper ;
    @Autowired
    CodeMappingMapper codeMappingMapper ;
    @Autowired
    private WarehouseMapper warehouseMapper;

    @Autowired
    IfPostbackService ifPostbackService ;
    @Autowired
    private CodeMappingService codeMappingService;

    @Reference(version = "${dubbo.consumers.basic.vendor.api:1.0.0}", check = false, timeout = 300000)
    private BasicVendorApi basicVendorApi;


    //调拨单回写
    public  void outStoreAsnWriteBack(TransferHeader header, List<TransferDtl> dtlList ,String transferType) {
        //查询供应商
        String vendorCode = "";
        String type = "";

        //转换单据类型
        switch (transferType) {
            case "T07": //不同库位调拨
                type = "5";
                break;
            case "T08": //报废出库单冻结【特殊处理】
                type = "4";
                break;
        }

        //生成回写数据
        List<ZDT_071_ReqCDK> list = new ArrayList<>();
        for (TransferDtl dtl : dtlList) {
            ZDT_071_ReqCDK record = new ZDT_071_ReqCDK();
            //转换单据类型TODO
            record.setBUDAT(DateUtil.format(new Date(), "yyyyMMdd"));
            record.setBZTP(type);//1：内销售后领料单；D14
                                    /*2：申购出库单：D15
                                    3:交货出库单
                                    4、报废出库单冻结
                                    4.1 报废单出库单过账 D16
                                    5、不同库位调拨
                                    6、工厂间调拨
                                    7、在途调拨
                                    8、标准委外领料出库D12
                                    9、标准委外退本厂*/
            record.setCKDNO(header.getTransferNo());//送货单号
            record.setCKDITEM(dtl.getTransferLineNo()+""); //送货单行号
            record.setEBELN(dtl.getToPo()==null?"":dtl.getToPo());//采购订单号
            record.setEBELP(" ");//采购订单行号
            record.setWMSID(header.getTransferHeaderId()+"");
            record.setLIFNR(vendorCode);//供应商代码  当单据类型为标准委外领料单出库、标准委外退本厂时，此字段为必输
            record.setWERKS(dtl.getToFactory());//工厂
            Sku sku = skuMapper.selectById(dtl.getToSku());
            if(sku==null){
                String message = String.format("未找到ID为【%s】的SKU信息",dtl.getToSku());
                Shift.fatal(StatusCode.BUSINESS_ERR, message);
            }
            record.setMATNR(sku.getSkuCode());//物料
            record.setMENGE(dtl.getCmpQty()+"");//数量
            //查询仓库
            Warehouse fmWarehouse = warehouseMapper.selectById(header.getFmWhs());
            CodeMapping fmCodeMapping = codeMappingService.selectByWhsCodeAndFactoryOrQaStatus(dtl.getFmFactory(), fmWarehouse.getWhsCode(),null);
            Warehouse toWarehouse = warehouseMapper.selectById(header.getToWhs());
            CodeMapping toCodeMapping = codeMappingService.selectByWhsCodeAndFactoryOrQaStatus(dtl.getToFactory(), toWarehouse.getWhsCode(),null);
            record.setLGORT(fmCodeMapping.getMappingCode());//移出库存地点
            //暂存自定义字段5
            record.setUMLGO(toCodeMapping.getMappingCode());//移入库存地点  当单据类型为1、内销售后领料单，4、报废出库单冻结，5、不同库位调拨，9、标准委外退本厂 此字段为必输

            list.add(record);
        }
        String jsonString = JSON.toJSONString(list);

        //插入数据到待回传数据表
        IfPostback ifPostback = new IfPostback();
        ifPostback.setDestSystem(OtherSystemEnum.SYSYTEM_SAP.getEnumName());
        ifPostback.setPostbackNo(header.getTransferNo());
        //TODO 待调整
        ifPostback.setPostbackTopic(TopicEnum.TOPIC_SAP_OUT_STORE.getEnumName());
        ifPostback.setPostbackContent(jsonString);
        ifPostback.setPostbackResult(BackResultEnum.DEFAULT_STATE.getCode());
        ifPostback.setCreateTime(new Date());
        ifPostback.setDestSystem(OtherSystemEnum.SYSYTEM_SAP.getEnumName());
        try {
            ifPostbackService.addOne(ifPostback);//保存
        } catch (Exception e) {
            e.printStackTrace();
            Shift.fatal(StatusCode.SERVER_MODIFY_ERROR);
        }
    }




}
